function MainCtrl($scope,kps,location, $cookieStore, $cookies, $document,$timeout,$rootScope,settings){
    $scope.settings=settings.getSettings();
    $scope.tooltipOption=$scope.settings.tooltipOption;
    
    //A varible used to determin UI behaviour
    var dragging = false;
    //Initializing application as unlocked
    $rootScope.locked=false;
    //Hook up empty user list from kaffipad.services
    $scope.users = kps.getAllUsers();
    
    kps.addUsers(kps.readCookieUsers($cookies));
    // Generate dummyusers if no user exists
    // TODO: Fjernes?
    if($scope.users.length==0){
        kps.addUsers(kps.generateUsers(10));
    }
    
    var cookieConsumptions = kps.readCookieConsumptions($cookies);
    for (var i = 0; i < cookieConsumptions.length; i++) {
        var u = kps.getUserByEmail(cookieConsumptions[i].getEmail());
        if (u != null) {
            kps.addConsumption(u,cookieConsumptions[i],$cookieStore, $document, $cookies);
        }
    }
    
    //TEST CODE TO AVOID LOGGING IN TASSOTER EVERY TIME(The code relies on the fact that user 'tassoter@gmail.com' is registerd on this device)
    var tassoter=kps.getUserByEmail('tassoter@gmail.com')
    kps.unlockUser(tassoter,'5e384d49fe8f25239bce2c9cca9a78bd');
    
    //Function for polling Yast service
    function startPoll($cookies){
        kps.poll($cookieStore, $document, $cookies);
        $scope.offline=kps.offline();
        $timeout(
            function(){
                startPoll($cookies);
            }
            ,10000);
    }
    
    //Function to fade in overlay if application is locked
    function lockCheck(){
        if($rootScope.locked){
            $('#lockOverlay').fadeIn(500);
        }
        $timeout(
            function(){
                lockCheck();
            }
            ,5000);
    }
    lockCheck();
    
    //Start updating userInfo as soon as users are loaded
    startPoll($cookies);
    
    // Code for user interface
    $(function() {
        //Activating tooltips on the document
        $(document).tooltip();
        // Creating droppable fields
        $("#userFunctions,#configurationFunctions,#lockFunctions").droppable({
            tolerance: "touch",
            over: function() {
                highlight($(this));
            },
            out: function() {
                lowlight($(this));
            }
        });
        $("#userFunctions").on("dropactivate", function(event, ui) {
            dragging = true;
            highlight(ui.draggable);
            $(".appIcon").hide();
            $(".userIcon").show();
            $(".user").css("cursor", "url(img/cursors/cursor_drag_hand_icon.png), default");
//            if(help){
            if(_.isEqual(settings.tooltipOption,"active"))showVisibleTooltipElements();
        });
        $("#userFunctions").on("dropdeactivate", function(event, ui) {
//            if(help){
            if(_.isEqual(settings.tooltipOption,"active"))hideVisibleTooltipElements();
            lowlight(ui.draggable);
            $(".appIcon").show();
            $(".userIcon").hide();
            $(".user").css("cursor", "url(img/cursors/cursor_hand_icon.png), default");
        });
        
        // Remove user from group
        $("#userFunctions").on("drop", function(event, ui) {
            lowlight($(this));
            var currentUser = getUserFromDraggable(ui.draggable);
            kps.removeUser(currentUser);
            var name = currentUser.stampUser.values.name;
            var email = currentUser.stampUser.values.email;
            $scope.userMessage("Removing user " + name + " (" + email + ") from group...", "response");
            $scope.removeCookie(email);
        });
        
        // User configuration
        $("#configurationFunctions").on("drop", function(event, ui) {
            lowlight($(this));
            var currentUser = getUserFromDraggable(ui.draggable);
            var email = currentUser.stampUser.values.email;
            $scope.userMessage("Drop " + email + " on config function...", "response");
        });
        
        // Lock user
        $("#lockFunctions").on("drop", function(event, ui) {
            lowlight($(this));
            var currentUser = getUserFromDraggable(ui.draggable);
            var name = currentUser.stampUser.values.name;
            var email = currentUser.stampUser.values.email;
            if (currentUser.stampUser.isLocked()) {
                $scope.userMessage("User " + name + " (" + email + ") is already locked!", "error");
            } else {
                kps.lockUser(currentUser);
                $scope.putCookie(currentUser.stampUser.values.email, kps.buildUserCookie(currentUser), 14);
                $(ui.draggable[0]["children"][1]["children"][1]["children"][0]).hide();
                $(ui.draggable[0]["children"][1]["children"][1]["children"][1]).hide();
                $(ui.draggable[0]["children"][1]["children"][1]["children"][2]).show();
                $(ui.draggable[0]["children"][2]).show();
                $scope.userMessage("Locking user " + name + " (" + email + ") ...", "response");
            }
        });
    })
    
    //A method showing the title attribute for visible elements
    function showVisibleTooltipElements(){
        $("[title]").filter(function(){return $(this).css('display')!='none';}).mouseover();
    }
    //A method hiding the title attribute for visible elements
    function hideVisibleTooltipElements(){
        $("[title]").filter(function(){return $(this).css('display')!='none';}).mouseout();
    }
    
    //A method showing the title attribute for visible elements for a given time
    function flashVisibleTooltipElements(time){
        showVisibleTooltipElements();
        $timeout(
            function(){
                hideVisibleTooltipElements();
            }
            ,time
        );
        
    }
    
    // Functions for retrieving a User object from a draggable div element
    var getUserFromDraggable = function(element) {
        var email = getUserEmail(element);
        var currentUser = kps.getUserByEmail(email);
        return currentUser;
    }
    var getUserEmail = function(element) {
        var outerDiv = element[0];
        var grandChild = outerDiv["children"][1]["children"][0];
        var email = $(grandChild).attr("data-email");
        return email;
    }
    
    // Functions for highlighting and "lowlighting" (un-highlighting) a div element
    var highlight = function(element) {
        element.css('z-index', 900);
        element.css('border-color', 'black');
    }
    var lowlight = function(element) {
        var bg = element.css('backgroundColor');
        element.css('z-index', highlightZIndex);
        element.css('border-color', bg);
    }
    var highlightZIndex = 0;
    // Code for user interface end
    
    //The color related to the specified userMessageTypes
    $scope.userMessageTypes = {
        response: 'green',
        error: 'red',
        help: 'blue'
    };
    
    // Function for navigating to the main page
    $scope.home = function() {
        location.path("/home");
    }
    
    // A function to display messages to user
    $scope.userMessage = function(message, type) {
        //Prints out the message to console
        console.log("MainCtrl(): userMessage(): type = '" + type + "': " + message);
        // Set color of message
        for(messageType in $scope.userMessageTypes) {
            if (_.isEqual(type, messageType)) {
                $("#userResponse").css('color', $scope.userMessageTypes[messageType]);
            }
        }
        // Write message, set to fade
        $("#userResponse").html(message)
        .fadeIn(200, function() {
            setTimeout(function() {
                $("#userResponse").fadeOut(500);
            }, 2000);
        })
    }
    
    // Lock app function stops all user interactions, and notifies the 
    // kaffipasService so it can deal with security aspects of the event
    $scope.lockApp = function() {
        kps.lockAllUsers();
        $rootScope.locked=true;
    }
    
//    // Prepare unlock attempt
    $scope.unlockAttempt = function() {
        // Locks header functions
        $(".appIcon").hide();
        $(".lockedIcon").show();
        // Hides lock icons
        $("#lockFunctions").hide();
        // Redirect to login page
        location.path("/login");
        // Fade out lock overlay
        $('#lockOverlay').fadeOut(500);
    }
    
    $scope.gotoUnlockUser = function(user) {
        if (dragging) {
            dragging = false;
        } else {
            location.path("/login");
            var name = user.stampUser.values.name;
            var email = user.stampUser.values.email;
            $scope.newName = name;
            $scope.newEmail = email;
        }
    }
    
    
    //    var findUserDiv = function(user) {
    //        var userIndex = -1;
    //        for (var i = 0; i < kps.getAllUsers().length; i++) {
    //            if (_.isEqual(user.stampUser.values.email, kps.getAllUsers()[i].stampUser.values.email)) userIndex = i;
    //        }
    //        
    //        if (userIndex < 0) return null;
    //        var scp = $("#page");
    //        var userDiv = scp[0]["children"][0]["children"][userIndex];
    //        return userDiv;
    //    }



    // Register a consumtion for the given user
    $scope.registerCoffeeConsumed = function(kpUser,consumption) {
        // Do not register consumption if user div was dragged
        if (dragging || kpUser.stampUser.isLocked()) {
            dragging = false;
        } else {
            kps.addConsumption(kpUser,consumption,$cookieStore, $document, $cookies);
        }
    }

    // Cookies 
    $scope.getCookie = function(key) {
        return kps.getCookie($cookieStore, key);
    }
    $scope.putCookie = function(key, value, daysUntilExpiration) {
        kps.putCookie($document, key, value, daysUntilExpiration);
    }
    $scope.removeCookie = function(key) {
        kps.removeCookie($cookieStore, key);
    }
    
}
MainCtrl.$inject=['$scope','KaffipadService','$location', '$cookieStore', '$cookies', '$document','$timeout','$rootScope','KaffipadSettings'];